package com.hqq.leetcode.dp;

import java.util.Scanner;

/**
 * MinPlalindromeSum 最小回文数组和
 * Description:
 * 给定一个数组 补充数字使得它是回文 要求得到的数组和最小
 * Input:
 * [1, 2, 3, 2, 1, 2],6
 * Output:
 * 11
 * Created by heqianqian on 2017/9/17.
 */
public class MinPlalindromeSum {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int sum = 0;
        int[] array = new int[n];
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
            sum += array[i];
        }
        System.out.println(sum + new MinPlalindromeSum().min(array, n));
        scanner.close();
    }

    public int min(int[] array, int n) {
        int[][] dp = new int[n][n];
        for (int i = n - 2; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                if (array[i] == array[j]) {
                    dp[i][j] = dp[i + 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i + 1][j] + array[i], dp[i][j - 1] + array[j]);
                }
            }
        }
        return dp[0][n - 1];
    }
}
